//
//  StatusListsViewModel.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/19.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SDWebImage

/// 微博视图模型
class StatusListsViewModel {
    
    /// 保存首页微博数据的数组
    lazy var statusListView = [StatusViewModel]()
    
    var newStatusCount:Int?
    
    ///  加载首页数据
    ///
    ///  - parameter finishedBlock: 回调
    func loadHomeInfo(ispullMoreData ispullMoreData: Bool, finishedBlock:(isSuccessed:Bool)->()){
        
        let since_id = ispullMoreData ? 0 : statusListView.first?.status.id ?? 0
        
        let max_id = ispullMoreData ? statusListView.last?.status.id ?? 0 : 0
        
        StatusDAL.loadStatusData(since_id, max_id: max_id) { (array) -> () in
            
            guard let array = array else{
                finishedBlock(isSuccessed: false)
                return
            }
            
            // 字典转模型
            var statusLists = [StatusViewModel]()
            
            for dict in array{
                
                statusLists.append(StatusViewModel(status: StatusModel(dict: dict)))
            }
            
            if max_id > 0 {
                
                self.statusListView += statusLists
                
            }else {
                
                self.statusListView = statusLists + self.statusListView
                
                self.newStatusCount = statusLists.count
            }
            print("新加载了" + "\(statusLists.count)")
            
            self.cacheSingleImage(statusLists, finishedBlock:finishedBlock)
        }
    }
    
    ///  缓存单张图片
    ///
    ///  - parameter statusLists: 完成单张图片缓存后,通知tableView 刷新界面
    private func cacheSingleImage(statusLists:[StatusViewModel], finishedBlock:(isSuccessed:Bool)->()){
        
        let group = dispatch_group_create()
        
        for sv in statusLists {
            
            if sv.pictureUrls?.count == 1 {
                
                dispatch_group_enter(group)
                                
                SDWebImageManager.sharedManager().downloadImageWithURL(sv.pictureUrls![0], options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
                        
            finishedBlock(isSuccessed: true)
        }
    }
}

